#include "type.h"

typedef struct user
{
	char username[25];
	char password[25];
	int gid, uid;
	char fullname[50];
	char homedir[50];
	char program[50];
} User;

int getUser(char* username, char* password, User* u);
void main(int argc, char* argv[])
{
	int stdin, stdout, stderr;
	char userName[25], password[25];
	User loginUser;
	
	close(0); close(1); close(2);
	
	stdin  = open(argv[1], READ);
	stdout = open(argv[1], WRITE);
	stderr = open(argv[1], WRITE);
	
	do_settty(argv[1]);
	
	printf("JRLOGIN: Opened %s as stdin, stdout, stderr\n", argv[1]);
	printf("-------------------------------------------------------\n");
	do_signal(2, 1);
	
	do
	{
		printf("Username: ");
		gets(userName);
		
		printf("Password: ");
		gets(password);
		
		if (getUser(userName, password, &loginUser) == 0)
		{			
			printf("\nWelcome %s!\n\n", loginUser.fullname);
			
			do_setuid(loginUser.uid);
			do_chdir(loginUser.homedir);
			do_exec(loginUser.program);
		}
		
		printf("Invalid username or password\n\n");
		
	} while (1);
}

int getUser(char* username, char* password, User* u)
{
	char file[1024], *tok = 0;
	int passwdFile = open("/etc/passwd", READ);
	
	do_read(passwdFile, file, 1024);
	
	tok = strtok(file, ":");
	while (tok != 0)
	{
		// Check if this line is the requested user
		if (strcmp(username, tok) == 0)
		{
			tok = strtok(0, ":");
			strcpy(u->username, tok);
			
			// Check if the password is correct
			if (strcmp(password, tok) == 0)
			{
				strcpy(u->password, tok);
				
				// Get the gid
				tok = strtok(0, ":");
				u->gid = atoi(tok);
				
				// Get the uid
				tok = strtok(0, ":");
				u->uid = atoi(tok);
				
				// Get the fullname
				tok = strtok(0, ":");
				strcpy(u->fullname, tok);
				
				// Get the home director
				tok = strtok(0, ":");
				strcpy(u->homedir, tok);
				
				// Get the program
				tok = strtok(0, ":\n");
				strcpy(u->program, tok);
				
				return 0;
			}
		}
		strtok(0, "\n");
		tok = strtok(0, ":");
	}
	return 1;
}






